package Sys_Module;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

public class Log_Module {
    private String file_localtion = ""; // LOG文件地址
    private FileReader file_reader; // 新建reader file对象
    private FileWriter file_writer; // 新建writer file对象
    private BufferedReader Buff_reader; // 新建buff reader 对象
    private BufferedWriter Buff_writer; // 新建buff writer 对象
    private Calendar ca_data;// 初始化日期对象

    public Log_Module(String localtion) throws IOException {
        this.file_localtion = Log_File_Name(localtion);
        try {
            file_reader = new FileReader(file_localtion);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            file_writer = new FileWriter(file_localtion, true); // 第二个参数为true 允许对日志文件的续写
        } catch (IOException e) {
            e.printStackTrace();
        }
        Buff_reader = new BufferedReader(file_reader);
        Buff_writer = new BufferedWriter(file_writer);
        Buff_writer.flush();
        Write_log("init", "加载日志模块完毕");
    }

    private String Log_File_Name(String name) throws IOException {
        ca_data = Calendar.getInstance(); // 初始化对象
        String temp; // 临时变量

        temp = name + " " + String.valueOf(ca_data.get(Calendar.YEAR)) + "-"
                + String.valueOf(ca_data.get(Calendar.MONTH) + 1) + "-" + String.valueOf(ca_data.get(Calendar.DATE))
                + ".log";// 输出当前期
        File temp_file = new File(temp);
        if (temp_file.exists() == false) { // 检测文件是否存在
            temp_file.createNewFile(); // 如果文件不存在则创建
        }
        return temp;
    }

    public String Read_log() throws IOException {
        String temp = "", temp2 = "";
        while ((temp = Buff_reader.readLine()) != null) {
            temp2 = temp2 + temp;
        }
        return temp2;
    }

    public synchronized void Write_log(String type, String message) throws IOException // 第一个参数为类型，第二个参数为信息
    {
        ca_data = Calendar.getInstance();
        String nowtime = String.valueOf(ca_data.getTime());
        Buff_writer.write(String.valueOf(nowtime) + " " + type + " " + message);
        Buff_writer.newLine();
        Buff_writer.flush();
    }

    @Override
    protected void finalize() throws Throwable { // 析构函数 定义
        super.finalize();
        Buff_reader.close();
        Buff_writer.close();
        file_reader.close();
        file_writer.close();
    }
}
